package com.project.template.controller;

import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.template.common.PageVO;
import com.project.template.common.Result;
import com.project.template.entity.Comments;
import com.project.template.entity.Posts;
import com.project.template.entity.SysUser;
import com.project.template.service.CommentsService;
import com.project.template.service.PostsService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

/**
 * 功能：
 * 作者：lhp
 * 日期：2025/3/19 21:29
 */
@RestController
@Slf4j
@RequestMapping("/comments")
public class CommentsController {

    @Resource
    private CommentsService commentsService;
    @Resource
    private PostsService postsService;

    @ApiOperation(value = "列表",notes = "列表")
    @GetMapping("/list")
    private Result<List<Comments>> list(){
        return new Result().success(commentsService.list());
    }

    @GetMapping("/page")
    public Result<PageVO<Comments>> findPage(
            @RequestParam Map<String,Object> query,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize
    ){
        Page<Comments> page= commentsService.page(query,pageNum,pageSize);
        return new Result().success(new PageVO<>(page));
    }

    @PostMapping("/add")
    public Result add(@RequestBody Comments comments){
        int length = comments.getLength();
        int id = comments.getPostId();
        LambdaQueryWrapper<Posts> wrapper = new LambdaQueryWrapper<>();
        if(id != 0){
            wrapper.eq(Posts::getId, id).last("limit 1");
            Posts posts = postsService.getOne(wrapper);
            posts.setLength(length);
            if(posts != null){
                commentsService.save(comments);
                postsService.updateById(posts);
            }else{
                return new Result().error("添加失败");
            }
        }
        return new Result<>().success();
    }

    @PutMapping("/update")
//    @Validated
    public Result updateById(@RequestBody Comments comments){
        commentsService.updateById(comments);
        return new Result<>().success();
    }

    @DeleteMapping("/delBatch")
    public Result delBatch(@RequestBody List<Integer> ids){
        commentsService.removeByIds(ids);
        return new Result().success();
    }
}
